package com.baikeyang.modules.thread;

import com.baikeyang.app.aspect.SysLogAspect;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;

/**
 * Created by lenovo on 2019/7/3.
 */
public class DaemonThreadDemo {

    public static void main(String[] args) {
        System.out.println("进入主线程:" + Thread.currentThread().getName());
        DaemonThread daemonThread = new DaemonThread();
        Thread thread = new Thread(daemonThread);
        thread.setDaemon(true);
        thread.start();

        Scanner s = new Scanner(System.in);
        String input = s.next();
        System.out.println(input);

        System.out.println(System.getProperty("java.version"));
        System.out.println("退出主线程:" + Thread.currentThread().getName());
    }

}

class DaemonThread implements Runnable {

    @Override
    public void run() {

        // TODO Auto-generated method stub
        System.out.println("进入守护线程:" + Thread.currentThread().getName());

        try {
            writeToFile();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("退出守护线程:" + Thread.currentThread().getName());
    }

    private void writeToFile() throws IOException, InterruptedException {
        File f = createFile("d：" + File.separator + "daemonDemo.txt");
        OutputStream os = new FileOutputStream(f);
        int count = 0;
        while (count < 99) {
            os.write(("\r\nword"+count+"QQ").getBytes());
            System.out.println("守护线程" + Thread.currentThread().getName()
                    + "向文件中写入word" + count++);
            Thread.sleep(1000);

        }

    }

    private File createFile(String path) throws IOException {
        File f = new File(path);
        String ret = "创建失败";
        if(!f.exists()){// 不存在则创建文件

            if(!f.getParentFile().exists()){// 判断父级目录是否存在，不存在则创建目录
                f.getParentFile().mkdirs();
            }

            boolean createFile = f.createNewFile();
            if(createFile){
                ret = "创建成功";
            }
        }
        System.out.println(ret);
        return f;
    }

}
